﻿#include "ChatServer.h"
#include "ClientHandler.h"
#include <iostream>

bool ChatServer::start(int port) {
    WSADATA wsaData;
    if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
        std::cerr << "WSAStartup failed!" << std::endl;
        return false;
    }

    listenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (listenSocket == INVALID_SOCKET) {
        std::cerr << "Socket creation failed!" << std::endl;
        return false;
    }

    sockaddr_in serverAddr{};
    serverAddr.sin_family = AF_INET;
    serverAddr.sin_addr.s_addr = INADDR_ANY;
    serverAddr.sin_port = htons(port);

    if (bind(listenSocket, (sockaddr *)&serverAddr, sizeof(serverAddr)) ==
        SOCKET_ERROR) {
        std::cerr << "Bind failed!" << std::endl;
        return false;
    }

    if (listen(listenSocket, SOMAXCONN) == SOCKET_ERROR) {
        std::cerr << "Listen failed!" << std::endl;
        return false;
    }

    std::cout << "聊天服务器启动，监听端口 " << port << std::endl;

    while (running) {
        sockaddr_in clientAddr{};
        int addrLen = sizeof(clientAddr);
        SOCKET clientSock =
            accept(listenSocket, (sockaddr *)&clientAddr, &addrLen);

        if (clientSock == INVALID_SOCKET) {
            std::cerr << "Accept failed!" << std::endl;
            continue;
        }

        // 为每个客户端启动独立线程
        std::thread clientThread([this, clientSock]() {
            ClientHandler handler(clientSock, this->userManager);
            handler.run();
        });
        clientThread.detach();
    }

    return true;
}

void ChatServer::stop() {
    running = false;
    if (listenSocket != INVALID_SOCKET) {
        closesocket(listenSocket);
    }
    WSACleanup();
}

ChatServer::~ChatServer() { stop(); }